<template>
  <a-dropdown>
    <slot>
      <a-button class="gray-outline" size="medium">保存为模板<icon-down /></a-button>
    </slot>
    <template #content>
      <a-doption v-if="currentTemp && currentTemp.id" @click.stop="uplateTemplate">覆盖当前模板</a-doption>
      <a-doption @click.stop="showCreateTempDialog = true">另存新模板</a-doption>
    </template>
  </a-dropdown>
  <a-modal v-model:visible="showCreateTempDialog" width="400px" :on-before-ok="submitData" title="请输入模板名称" title-align="start" :mask-closable="false" :ok-loading="createTemplateLoading" @cancel="tempEditName = ''">
    <a-input v-model="tempEditName" />
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, defineComponent } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { createTemplate, updateTemplate } from '@/api/export'
  const emit = defineEmits(['success'])
  const props = defineProps({
    currentTemp: {
      type: Object,
      default: () => {},
    },
    templateCode: {
      type: String,
    },
    content: {
      type: Object,
      default: () => {},
    },
  })

  const showCreateTempDialog = ref(false)
  const tempEditName = ref('')
  const createTemplateLoading = ref(false)

  // 更新模板模板
  async function uplateTemplate() {
    const res: any = await updateTemplate({
      templateType: 2,
      templateCode: props.templateCode,
      id: props.currentTemp.id,
      templateContent: JSON.stringify(props.content),
    })
    if (res) {
      Message.success('覆盖当前模板成功！')
      emit('success')
    }
  }
  // 保存模板
  async function submitData() {
    if (!tempEditName.value) {
      Message.error('请输入模板名称！')
      return false
    }
    const res: any = await createTemplate({
      enable: true,
      templateCode: props.templateCode,
      templateName: tempEditName.value,
      templateContent: JSON.stringify(props.content),
      templateType: 2,
    })
    if (!res) return false
    Message.success('模板创建成功')
    showCreateTempDialog.value = false
    tempEditName.value = ''
    emit('success')
  }
</script>
<script lang="ts">
  export default defineComponent({
    name: 'AddPrintTemp',
  })
</script>
